//
//  DiaryDetailController.m
//  MyTrip
//
//  Created by zhang on 15/8/25.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "DiaryDetailController.h"
#import "DetailHeaderView.h"
#import "AsyncGETConnection.h"
#import "Diary.h"
#import "DiaryDetailHeader.h"
#import "DayCell.h"
#import "DiaryDataBase.h"
#import "MBProgressHUD.h"
#define Width [[UIScreen mainScreen] bounds].size.width

@interface DiaryDetailController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *detailTable;
@property (nonatomic, retain) NSMutableArray *detailArray;
@property (nonatomic, retain) DetailHeaderView *detailHeaderView;
@property (nonatomic, retain) NSMutableArray *daysArray;
@property (nonatomic, retain) MBProgressHUD *hud;


@end

@implementation DiaryDetailController

- (void)dealloc
{
    [_daysArray release];
    [_detailHeaderView release];
    [_detailTable release];
    [_detailArray release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.detailArray = [NSMutableArray array];
        self.daysArray = [NSMutableArray array];
    }
    return self;
}
- (void)getMessage{
    self.hud = [[MBProgressHUD alloc] init];
    [self.view addSubview:_hud];
    [_hud show:YES];
    _hud.labelText = @"正在拼命加载......";
    //    在网络请求之后
    
    __block MBProgressHUD *hud = _hud;
    [AsyncGETConnection asyncGETConnectionWithURLStr:[NSString stringWithFormat:@"http://api.breadtrip.com/trips/%ld/waypoints/", _diary.diaryid] parameters:nil messageBlock:^(NSData *data) {
        hud.hidden = YES;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *user = [dic objectForKey:@"user"];
        DiaryDetailHeader *diary = [DiaryDetailHeader diaryDetailWithHeaderImage:[dic objectForKey:@"cover_image"] authorImage:[user objectForKey:@"avatar_m"] authorName:[user objectForKey:@"name"] title:[dic objectForKey:@"name"] startTime:[dic objectForKey:@"first_day"] days:[[dic objectForKey:@"day_count"] integerValue] mileage:[[dic objectForKey:@"mileage"] integerValue] like:[[dic objectForKey:@"recommendations"] integerValue]];
        [_detailHeaderView setValueWithModel:diary];
        NSArray *days = [dic objectForKey:@"days"];
        [_daysArray addObjectsFromArray:days];
        [_detailTable reloadData];
    }];
    
}




- (void)createTable{
    self.detailTable = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped] autorelease];
    _detailTable.delegate = self;
    _detailTable.dataSource = self;
    [_detailTable registerClass:[DayCell class] forCellReuseIdentifier:@"day"];
    [self.view addSubview:_detailTable];
    
    self.detailHeaderView = [[[DetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 400 * OffHeight)] autorelease];
    _detailTable.tableHeaderView = _detailHeaderView;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _daysArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = [_daysArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:@"waypoints"];
    
    return [array count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = [_daysArray objectAtIndex:indexPath.section];
    NSArray *array = [dic objectForKey:@"waypoints"];
    NSDictionary *localDic = [array objectAtIndex:indexPath.row];
    return [DayCell hightWithIndexPathOfDic:localDic];
}





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DayCell *cell = [tableView dequeueReusableCellWithIdentifier:@"day"];
    NSDictionary *dic = [_daysArray objectAtIndex:indexPath.section];
    NSArray *array = [dic objectForKey:@"waypoints"];
    NSDictionary *dayDic = [array objectAtIndex:indexPath.row];
    [cell createViewWithDic:dayDic];
    return cell;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0f green:160 / 255.0f blue:175 / 255.0f alpha:1];
    

    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self createTable];
    [self getMessage];
    
    UIButton *button  = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 20)] autorelease];
    [button addTarget:self action:@selector(barButtonItemAction:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"save.png"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


- (void)barButtonItemAction:(UIBarButtonItem *)sender{
    
    Diary *diary = [DiaryDataBase selectWithDiaryid:_diary.diaryid];
    if (diary) {
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"已收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [alter addAction:action];
        [self presentViewController:alter animated:YES completion:^{
            
        }];
    }else{
        [DiaryDataBase insertWithDiary:_diary];
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [alter addAction:action];
        [self presentViewController:alter animated:YES completion:^{
            
        }];
    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
